/*
 * @Description: 
 * @Author: JP
 * @Date: 2018-12-07 15:47:54
 * @LastEditors: JP
 * @LastEditTime: 2018-12-14 16:50:41
 */
// pages/wifi/wifi.js
function Detail(ssid, bssid, signalStrength) {
  this.ssid = ssid;
  this.bssid = bssid;
  this.signalStrength = signalStrength;
}

function Info() {
  this.details = [];
}

Page({

  /**
   * 页面的初始数据
   */
  data: {
    id: 'api',
    color: '',
    platform: 'android',
    ssid: '',
    bssid: '',
    pass: '',
    connectedSsid: '',
    info: {}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.init();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    that.data.info = [];
    that.init();
    that.startWifi(that);
    if (this.data.pass == '') {
      this.setData({
        color: '#f0f0f0'
      });
    }
    that.GetConnectedList(that);
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  /**
   * 初始化 Wi-Fi 模块
   */
  startWifi: function (_this) {
    console.log("startWifi");
    wx.startWifi({
      success: function () {
        _this.getList(_this);
      },
      fail: function (res) {
        _this.setData({
          startError: res.errMsg
        });
        console.log(res.errMsg);
      }
    })
  },
  /**
   * 获取 Wi-Fi 列表
   */
  getList: function (_this) {
    console.log("getList");
    //安卓执行方法
    if (_this.data.platform == 'android') {
      //请求获取 Wi-Fi 列表
      wx.getWifiList({
        success: function (res) {
          //安卓执行方法
          _this.AndroidList(_this);
        },
        fail: function (res) {
          _this.setData({
            wifiListError: true
          });
          _this.setData({
            wifiListErrorInfo: res.errMsg
          });
        }
      })
    }
    //IOS执行方法
    if (_this.data.platform == 'ios') {
      _this.IosList(_this);
    }

  },
  /**
   * 初始化 Wi-Fi 列表，安卓平台
   */
  AndroidList: function (_this) {
    console.log("AndroidList");
    //监听获取到 Wi-Fi 列表数据
    wx.onGetWifiList(function (res) { //获取列表
      console.log(res.wifiList);
      if (res.wifiList.length) {
        // 过滤重复的 Wi-Fi
        var list = _this.filterScanResult(res.wifiList);
        console.log(list);
        _this.addItem(list);
        //执行连接方法
        //连接wifi
      //  _this.Connected(_this);
      }
    })
  },
  IosList: function (_this) {
    _this.setData({
      wifiListError: true
    });
    _this.setData({
      wifiListErrorInfo: 'IOS暂不支持'
    });
  },
  /**
   * 连接wifi
   */
  Connected: function (_this) {
    wx.connectWifi({
      SSID: _this.data.ssid,
      BSSID: _this.data.bssid,
      password: _this.data.pass,
      success: function (res) {
        console.log("wifi连接成功");
        _this.setData({
          endError: 'wifi连接成功',
          connectedSsid: _this.data.ssid
        });
      },
      fail: function (res) {
        console.log(res.errMsg);
        _this.setData({
          endError: res.errMsg
        });
      }
    })
  },
  /**
   * 获取系统已连接的 Wi-Fi列表
   */
  GetConnectedList: function (_this) {
    wx.getConnectedWifi({
      success(res) {
        _this.setData({
          connectedSsid: res.wifi.SSID
        });
        console.log("_this.data.connectedSsid:", _this.data.connectedSsid);
      },
      fail(res) {
        console.log(res.errMsg)
      }
    })
  },
  /**
   * 过滤重复的 Wi-Fi
   */
  filterScanResult: function (rst) {
    var list = [];
    list.push(rst[0]);
    var isNew = true;
    for (var i = 1; i < rst.length; i++) {
      isNew = true;
      for (var j = 0; j < list.length; j++) {
        if (rst[i].SSID == list[j].SSID) {
          isNew = false;
          if (rst[i].signalStrength > list[j].signalStrength) {
            list[j] = rst[i];
          }
        }
      }
      if (isNew) {
        list.push(rst[i]);
      }
    }
    return list;
  },

  init: function () {
    let that = this;
    this.setData({
      info: new Info()
    });
  },

  addItem: function (list) {
    let info = this.data.info;
    
    for (var i = 0; i < list.length; i++) {
      let detail = new Detail();
      detail.ssid = list[i].SSID;
      detail.bssid = list[i].BSSID;
      detail.signalStrength = list[i].signalStrength;
      info.details.push(detail);
    }
    this.setData({
      info: info
    });
  },
  removeItem: function (e) {
    let info = this.data.info;
    info.details.pop();
    this.setData({
      info: info
    });
  },
  setSsid: function (e) {
    let index = parseInt(e.currentTarget.id.replace("ssid-", ""));
    let place = e.detail.value;
    let info = this.data.info;
    info.details[index].ssid = ssid;
    this.setData({
      info: info
    });
  },

  setSignalStrength: function (e) {
    let index = parseInt(e.currentTarget.id.replace("signalStrength-", ""));
    let number = e.detail.value;
    let info = this.data.info;
    info.details[index].signalStrength = signalStrength;
    this.setData({
      info: info
    });
  },

  searchWifi: function () {
    var that = this;
    that.data.info = [];
    that.init();
    that.startWifi(that)
  },

  /**
   * 弹窗
   */
  showDialogBtn: function (e) {
    var index = e.currentTarget.dataset.index;
    this.setData({
      showModal: true,
      ssid: this.data.info.details[index].ssid,
      bssid: this.data.info.details[index].bssid,
      color: '#f0f0f0'
    })
  },
  /**
   * 弹出框蒙层截断touchmove事件
   */
  preventTouchMove: function () {},
  /**
   * 隐藏模态对话框
   */
  hideModal: function () {
    this.setData({
      showModal: false
    });
  },
  /**
   * 对话框取消按钮点击事件
   */
  onCancel: function () {
    this.hideModal();
  },
  /**
   * 对话框确认按钮点击事件
   */
  onConfirm: function () {
    if (this.data.pass != '') {
      this.Connected(this);
    }
    this.hideModal();
  },
  /**
   * 获取输入的密码
   */
  inputChange: function (e) {
    var val = e.detail.value;
    if (val != '') {
      this.setData({
        color: '#ec5300'
      });
    } else {
      this.setData({
        color: '#f0f0f0'
      });
    }
    this.setData({
      pass: val
    });
  },

  connectServer: function (e) {
    wx.connectSocket({
      url: 'ws://localhost:3000'
    })

    wx.onSocketOpen(function (res) {
      console.log('WebSocket连接已打开！')

      wx.sendSocketMessage({
        data: 'Hello,World:' + Math.round(Math.random() * 0xFFFFFF).toString(),
      })
    })

    wx.onSocketMessage(function (res) {
      console.log(res)
    })

    wx.onSocketClose(function (res) {
      console.log('WebSocket连接已关闭！')
    })
  },

  sendMsg: function (e) {
    wx.sendSocketMessage({
      data: 'Hello,World:' + Math.round(Math.random() * 0xFFFFFF).toString(),
    })
    wx.onSocketMessage(function (res) {
      console.log(res.data)
    })
  }

})
